package com.springboot2.shiro.mgt.filter;

import com.springboot2.shiro.auth.Constants;
import com.springboot2.shiro.data.enity.User;
import com.springboot2.shiro.data.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.PathMatchingFilter;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.util.Optional;

/**
 * LoginAccountFilter
 *
 * @author Archx[archx@foxmail.com]
 * at 2018/7/13 22:03
 */
public class LoginAccountFilter extends PathMatchingFilter {

    @Resource
    private UserService userService;

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @Override
    protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue)
            throws Exception {
        Subject subject = SecurityUtils.getSubject();
        String  login   = (String) subject.getPrincipal();

        User user = userService.findByLogin(login);
        Optional.ofNullable(user).ifPresent(u -> request.setAttribute(Constants.LOGIN_ACCOUNT, u));
        return true;
    }
}


